package com.gxa.community.admin.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.community.admin.advice.Log;
import com.gxa.community.admin.service.system.AdminService;
import com.gxa.community.admin.service.system.SystemService;
import com.gxa.community.admin.util.Md5Utils;
import com.gxa.community.core.pojo.domain.Admin;
import com.gxa.community.core.pojo.dto.system.AdminDTO;
import com.gxa.community.core.pojo.dto.system.AdminsDTO;
import com.gxa.community.core.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/system")
@Validated
@Api("账号管理")
public class SystemController {
    @Autowired
    private SystemService systemService;
    @Autowired
    private AdminService adminService;

    @ApiOperation("查询所有账号接口")
    @GetMapping("/getallacount")
    public R getAllAcount(@RequestParam("currentPage")Integer currentPage,@RequestParam("pageSize")Integer pageSize){
        PageHelper.startPage(currentPage, pageSize);
        //总的数据
        List<AdminDTO> list = systemService.list();
        if(list != null){
            //生成分页数据
            PageInfo<AdminDTO> pageInfo = new PageInfo<>(list);
            //总条数，总页数，当前页码，每页显示条数，当前页数据
            long total = pageInfo.getTotal();
            List<AdminDTO> currentList = pageInfo.getList();
            int pages = pageInfo.getPages();
            AdminsDTO adminsDTO = new AdminsDTO();
            adminsDTO.setTotal(total);
            adminsDTO.setPages(pages);
            adminsDTO.setCurrentPage(currentPage);
            adminsDTO.setPageSize(pageSize);
            adminsDTO.setUsers(currentList);
            return R.ok().put("data",adminsDTO);
        }else {
            return R.error(600,"查询失败，请联系管理员！！");
        }
    }

    @ApiOperation("按账号进行搜索（模糊搜索）")
    @GetMapping("/searchbyloginact")
    public R searchByLoginAct(@RequestParam("loginAct")String loginAct,@RequestParam("currentPage")Integer currentPage,@RequestParam("pageSize")Integer pageSize){
        if (StringUtils.isBlank(loginAct)){
            //如果搜索框输入为空，默认查询所有
            R result = this.getAllAcount(currentPage, pageSize);
            return result;
        }else {
            //先设置分页条件
            PageHelper.startPage(currentPage,pageSize);
            //封装搜索条件
            LambdaQueryWrapper<AdminDTO> adminDTOLambdaQueryWrapper = Wrappers.lambdaQuery(AdminDTO.class);
            adminDTOLambdaQueryWrapper.like(AdminDTO::getLoginAct,loginAct);
            List<AdminDTO> list = systemService.list(adminDTOLambdaQueryWrapper);
            if(list != null){
                //生成分页数据
                PageInfo<AdminDTO> pageInfo = new PageInfo<>(list);
                //总条数，总页数，当前页码，每页显示条数，当前页数据
                long total = pageInfo.getTotal();
                List<AdminDTO> currentList = pageInfo.getList();
                int pages = pageInfo.getPages();
                AdminsDTO adminsDTO = new AdminsDTO();
                adminsDTO.setTotal(total);
                adminsDTO.setPages(pages);
                adminsDTO.setCurrentPage(currentPage);
                adminsDTO.setPageSize(pageSize);
                adminsDTO.setUsers(currentList);
                return R.ok().put("data",adminsDTO);
            }else {
                return R.error(600,"查询失败，请联系管理员！！");
            }
        }
    }

    @ApiOperation("查询用户名是否可用接口")
    @GetMapping("/queryloginact")
    public R queryLoginAct(String loginAct){
        LambdaQueryWrapper<AdminDTO> adminDTOLambdaQueryWrapper = Wrappers.lambdaQuery(AdminDTO.class);
        adminDTOLambdaQueryWrapper.eq(AdminDTO::getLoginAct,loginAct);
        AdminDTO result = systemService.getOne(adminDTOLambdaQueryWrapper);
        if (result == null){
            return R.ok("恭喜你，该账号名可以使用！");
        }else {
            return R.error(600,"很遗憾，该账号名已被使用，请重新输入！");
        }
    }

    @ApiOperation("新建账户")
    @PostMapping("/addloginact")
    @Log(title = "",action = "新增了一个账号")
    public R addLoginAct(@Validated Admin admin){
        //对用户的密码进行MD5加密
        String password = admin.getPassword();
//        先 生成盐
        UUID uuid = UUID.randomUUID();
        admin.setSalt(uuid.toString());
        //将加密后的密码重新塞入admin
        admin.setPassword(Md5Utils.getCiphertext(password, ByteSource.Util.bytes(uuid.toString())));
        admin.setCreateTime(new Date().getTime());
        boolean result = adminService.save(admin);
//        log.info("id:{}",admin.getId());
//        boolean result = adminService.saveOrUpdate(admin);
        //存在更新记录，否插入一条记录
        return result?R.ok("创建成功！"):R.error(600,"创建失败，请联系管理员！！");
    }

    @ApiOperation("根据id查询单个账号")
    @GetMapping("/getsingleadmin/{id}")
    public R getSingleAdminById(@PathVariable("id") Integer id){
        LambdaQueryWrapper<AdminDTO> adminDTOLambdaQueryWrapper = Wrappers.lambdaQuery(AdminDTO.class);
        adminDTOLambdaQueryWrapper.eq(AdminDTO::getId,id);
        AdminDTO adminDTO = systemService.getOne(adminDTOLambdaQueryWrapper);
        return adminDTO != null?R.ok("查询成功！！").put("data",adminDTO):R.error(600,"查询失败，请联系管理员！！");
    }

    @ApiOperation("修改单个账号信息")
    @PutMapping("/updatesingleadmin")
    @Log(title = "",action = "修改了一个账号信息")
    public R updateSingleAdmin(@Validated Admin admin){
        String password = admin.getPassword();
        if (StringUtils.isNotBlank(password)){
            LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = Wrappers.lambdaQuery(Admin.class);
            adminLambdaQueryWrapper.eq(Admin::getId,admin.getId());
            Map<String, Object> map = adminService.getMap(adminLambdaQueryWrapper);
            log.info("map:{}",map);
            //获取当前用户的盐值
            String salt = (String) map.get("salt");
            admin.setSalt(salt);
            //将加密后的密码重新塞入admin
            admin.setPassword(Md5Utils.getCiphertext(password, ByteSource.Util.bytes(salt)));
        }
        boolean result = adminService.saveOrUpdate(admin);
        return result?R.ok("修改成功！"):R.error(600,"修改失败！");
    }
    @ApiOperation("删除单个账号")
    @DeleteMapping("/deletesingleadmin/{id}")
    @Log(title = "",action = "删除了一个账号")
    public R deleteSingleAdmin(@PathVariable("id") Integer id){
        boolean result = adminService.removeById(id);
        return result?R.ok("删除成功！"):R.error(600,"删除失败，请联系管理员！！");
    }
}
